const { sendResponse, sendListResponse } = require('../utils/response');
const QuestionCollection = require('../models/QuestionCollection');
const Question = require('../models/Question');
const User = require('../models/User');
const moment = require('moment');
const sequelize = require('sequelize');
const { formatObject } = require('../utils/common');
const QuestionCategory = require('../models/QuestionCategory');

// 收藏题目
exports.collectQuestion = async (req, res) => {
  const { userId, questionId } = req.body;

  try {
    // 检查是否已经收藏
    const existingCollection = await QuestionCollection.findOne({
      where: {
        user_id: userId,
        question_id: questionId
      }
    });

    if (existingCollection) {
      return sendResponse(res, 400, "该题目已收藏");
    }

    // 检查题目是否存在
    const question = await Question.findByPk(questionId);
    if (!question) {
      return sendResponse(res, 404, "题目不存在");
    }

    // 创建收藏记录
    await QuestionCollection.create({
      user_id: userId,
      question_id: questionId,
      collect_time: new Date()
    });

    sendResponse(res, 200, "收藏成功");
  } catch (error) {
    console.error("收藏失败:", error);
    sendResponse(res, 500, "收藏失败");
  }
};

// 取消收藏
exports.uncollectQuestion = async (req, res) => {
  const userId = req.body.userId;
  const questionId = req.body.questionId;

  try {
    // 查找并删除收藏记录
    const result = await QuestionCollection.destroy({
      where: {
        user_id: userId,
        question_id: questionId
      }
    });

    if (result === 0) {
      return sendResponse(res, 500, "未找到收藏记录");
    }

    sendResponse(res, 200, "取消收藏成功");
  } catch (error) {
    console.error("取消收藏失败:", error);
    sendResponse(res, 500, "取消收藏失败");
  }
};

// 获取用户收藏的题目列表
exports.getUserCollections = async (req, res) => {
  const userId = req.query.userId;
  const page = parseInt(req.query.page) || 1;
  const pageSize = parseInt(req.query.pageSize) || 10;
  const isDelete = req.query.isDelete;
  const difficulty = req.query.difficulty;
  const offset = (page - 1) * pageSize;

  try {
    // 构建Question模型的查询条件
    const questionWhere = {};
    if (isDelete !== undefined) {
      questionWhere.is_delete = isDelete;
    }
    if (difficulty !== undefined && difficulty !== '') {
      questionWhere.difficulty = difficulty;
    }

    // 使用关联查询获取收藏列表
    const { count, rows } = await QuestionCollection.findAndCountAll({
      where: { user_id: userId },
      include: [{
        model: Question,
        as: 'question',
        attributes: ['id', 'content', 'options', 'correct_key', 'difficulty', 'category_id', 'status', 'user_id', 'create_time'],
        required: true,
        where: questionWhere,
        include: [{
          model: QuestionCategory,
          as: 'category',
          attributes: ['id', 'name'],
          required: false
        }]
      }],
      order: [['collect_time', 'DESC']], // 按收藏时间倒序排列
      limit: pageSize,
      offset: offset,
      subQuery: false // 使用子查询来确保count正确
    });

    // 格式化返回数据
    const collections = rows.map(item => ({
      questionId: item.question_id,
      collectTime: moment(item.collect_time).format('YYYY-MM-DD HH:mm:ss'),
      question: {
        ...formatObject(item.question.toJSON()),
        categoryName: item.question.category?.name || '未分类'
      }
    }));

    sendListResponse(res, 200, "获取收藏列表成功", collections, count);
  } catch (error) {
    console.error("获取收藏列表失败:", error);
    sendResponse(res, 500, "获取收藏列表失败");
  }
};

// 检查题目是否已收藏
exports.checkCollection = async (req, res) => {
  const userId = req.query.userId;
  const questionId = req.query.questionId;

  try {
    const collection = await QuestionCollection.findOne({
      where: {
        user_id: userId,
        question_id: questionId
      },
      include: [{
        model: Question,
        as: 'question',
        attributes: ['content']
      }]
    });

    sendResponse(res, 200, "查询成功", {
      isCollected: !!collection,
      collectionInfo: collection ? {
        collectTime: moment(collection.collect_time).format('YYYY-MM-DD HH:mm:ss'),
        questionContent: collection.question.content
      } : null
    });
  } catch (error) {
    console.error("查询收藏状态失败:", error);
    sendResponse(res, 500, "查询收藏状态失败");
  }
};

// 获取题目的收藏数量
exports.getQuestionCollectionCount = async (req, res) => {
  const questionId = req.params.questionId;

  try {
    // 先检查题目是否存在
    const questionExists = await Question.findByPk(questionId);
    if (!questionExists) {
      return sendResponse(res, 500, "题目不存在");
    }

    // 使用更简单的查询方式获取收藏数量
    const collectionCount = await QuestionCollection.count({
      where: { question_id: questionId }
    });

    // 返回题目信息和收藏数量
    sendResponse(res, 200, "查询成功", formatObject({
      questionId: questionExists.id,
      content: questionExists.content,
      options: questionExists.options,
      difficulty: questionExists.difficulty,
      category_id: questionExists.category_id,
      status: questionExists.status,
      user_id: questionExists.user_id,
      create_time: questionExists.create_time,
      collectionCount: collectionCount || 0,
      is_deleted: questionExists.is_delete
    }));
  } catch (error) {
    console.error("获取收藏数量失败:", error);
    sendResponse(res, 500, "获取收藏数量失败", { error: error.message });
  }
}; 